import { reqCartList, reqDeleteCart, reqUppdateCheck } from "@/api"
const state = {
    cartList: []
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
}
const actions = {
    // 获取购物车列表
    async getCartList({ commit }) {
        let res = await reqCartList()
        // console.log(res)
        if (res.code == 200) {
            commit('GETCARTLIST', res.data)
        }
    },
    // 删除购物车产品
    async deleteCart({ commit }, skuId) {
        let res = await reqDeleteCart(skuId)
        if (res.code != 200) return Promise.reject(new Error('faile'))
        return 'success'
    },
    // 修改购物车产品的选中状态
    async uppdateCheck({ commit }, { skuId, isChecked }) {
        let res = await reqUppdateCheck(skuId, isChecked)
        if (res.code != 200) return Promise.reject(new Error('faile'))
        return 'success'
    },
    deleteAll({ dispatch, getters }) {
        // console.log(getters.cartList.cartInfoList)
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCart', item.skuId) : ''
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    },
    checkAll({ dispatch, state }, isChecked) {
        // console.log(state,isChecked)
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('uppdateCheck', { skuId: item.skuId, isChecked }) 
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
    // cartInfoList(state){
    //     return state.
    // }
}
export default {
    state, mutations, actions, getters
}